package com.cavy.platform.server.repository.impl;

import com.cavy.platform.server.domain.Agent;
import com.cavy.platform.server.repository.AgentRepository;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Repository
public class AgentRepositoryImpl implements AgentRepository {
    private static final String FILE_NAME = "agentMap.json";
    @Value("${cavy.agent.dir}")
    private String dir;
    private Map<String, Agent> map = new HashMap<>();

    @Override
    public Agent findByHostname(String hostname) {
        return map.get(hostname);
    }

    @Override
    public void add(String hostname, Agent agent) {
        save(agent);
    }

    @Override
    public void save(Agent agent) {
        map.put(agent.getHostname(), agent);
        save();
    }

    private void save() {
        File file = new File(dir, FILE_NAME);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            boolean mkdirs = parentFile.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建文件夹:" + parentFile.getPath() + "失败");
            }
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(file, map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(String agent) {
        map.remove(agent);
        save();
    }

    @Override
    public int count(String name) {
        Agent agent = map.get(name);
        if (agent != null) {
            return 1;
        }
        return 0;
    }

    @PostConstruct
    public void load() {
        File src = new File(dir, FILE_NAME);
        if (!src.exists()) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Agent.class);
        try {
            map = mapper.readValue(src, javaType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
